package com.lmsservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lmsservice.common.R;
import com.lmsservice.entity.Book;
import com.lmsservice.entity.Records;
import com.lmsservice.entity.Rules;
import com.lmsservice.entity.User;
import com.lmsservice.service.BookService;
import com.lmsservice.service.RecordService;
import com.lmsservice.service.RulesService;
import com.lmsservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;

    @Autowired
    private UserService userService;

    @Autowired
    private RecordService recordService;

    @Autowired
    private RulesService rulesService;

    @GetMapping
    public R<Page> getBook(Integer page,Integer pageSize,String name,String isbn,String author){
        Page<Book> bookPage = new Page<>(page , pageSize);
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!Objects.equals(name, ""),Book::getName,name)
                .like(!Objects.equals(isbn, ""),Book::getIsbn,isbn)
                .like(!Objects.equals(author, ""),Book::getAuthor,author);
        bookService.page(bookPage,queryWrapper);
        return R.success(bookPage);
    }

    @PostMapping
    public R<String> add(@RequestBody Book book){
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(!Objects.equals(book.getIsbn(), ""),Book::getIsbn,book.getIsbn());
        Book book1 = bookService.getOne(queryWrapper);
        if (book1!=null){
            return R.error("书籍已存在");
        }
        bookService.save(book);
        return R.success("添加成功");
    }

    @DeleteMapping
    public R<String> deleteById1(@RequestBody Book book){
        bookService.removeById(book);
        return R.success("删除成功");
    }

    @PutMapping
    public R<String> updateById(@RequestBody Book book){
        bookService.updateById(book);
        return R.success("修改成功");
    }

    @GetMapping("/list")
    public R<List<Book>> getlist(String name,String isbn,String author,String publisher){
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(isbn!=null&&!Objects.equals(isbn, ""),Book::getIsbn,isbn)
                .like(name!=null&&!Objects.equals(name, ""),Book::getName,name)
                .like(author!=null&&!Objects.equals(author, ""),Book::getAuthor,author)
                .like(publisher!=null&&!Objects.equals(publisher, ""),Book::getPublisher,publisher);

        List<Book> books = bookService.list(queryWrapper);

        return R.success(books);
    }

    @PostMapping("/borrow")
    @Transactional
    public R<String> borrowBook(@RequestBody Records records){
        User user = userService.getById(records.getUserId());
        Rules rules = rulesService.getById(1);
        Book book = bookService.getById(records.getBookId());
        if (book.getStock()-1<0){
            book.setStatus(0);
            bookService.updateById(book);
            return R.error("该图书已无库存");
        }
        book.setStock(book.getStock()-1);
        if (book.getStock()-1<0){
            book.setStatus(0);
        } else {
            book.setStatus(1);
        }
        bookService.updateById(book);
        if (user.getStatus()==0){
            return R.error("已违规,不能再借阅书籍");
        }
        if (user.getBorrowNum()+1> rules.getNums()){
            return R.error("借阅的书籍已达上限");
        }
        user.setBorrowNum(user.getBorrowNum()+1);
        userService.updateById(user);
        records.setBorrowTime(LocalDateTime.now());
        recordService.save(records);
        return R.success("借阅成功");
    }

    @PostMapping("/return")
    @Transactional
    public R<String> returnBook(@RequestBody Records records){
        Records records1 = recordService.getById(records.getId());
        records1.setReturnTime(LocalDateTime.now());
        Rules rules = rulesService.getById(1);
        User user = userService.getById(records1.getUserId());
        Book book = bookService.getById(records1.getBookId());
        user.setBorrowNum(user.getBorrowNum()-1);
        book.setStock(book.getStock()+1);
        if (book.getStock()>0){
            book.setStatus(1);
        }
        bookService.updateById(book);
        if (Duration.between(records1.getBorrowTime(), records1.getReturnTime()).toHours()> rules.getHours()){
            records1.setStatus(2);
            recordService.updateById(records1);
            user.setStatus(0);
            userService.updateById(user);
            return R.success("此次借阅已超时，账号将被封禁"+rules.getBanHours()+"h");
        }
        records1.setStatus(1);
        userService.updateById(user);
        recordService.updateById(records1);
        return R.success("归还成功");
    }
}
